<template>
    <div>
        <el-form size="large" :model="form">
            <div class="translation-container">
                <div class="translation-header">
                    <div class="translation-logo">
                        <img src="@/assets/logo/logo.png" alt="logo" width="50" height="50">
                        <div class="logo-title">TLate</div>
                    </div>
                    <div class="translation-product">
                        <el-select
                                @change="handleChangeProduct"
                                clearable v-model="form.productId" placeholder="请选择翻译产品">
                            <el-option v-for="product in productList" :key="product.productId"
                                       :label="product.productName"
                                       :value="product.productId"/>
                        </el-select>
                    </div>
                </div>
                <!--使用须知-->
                <NoticeForUse/>
                <div class="translation-main">
                    <div class="translation-form">
                        <div class="language-select">
                            <div class="from-language">
                                <el-select clearable filterable v-model="form.from" placeholder="请选择当前文本语言">
                                    <el-option v-for="language in languageList" :key="language.value"
                                               :label="language.label"
                                               :value="language.value"/>
                                </el-select>
                            </div>
                            <div class="icon"></div>
                            <div class="to-language">
                                <el-button @click="languageSelectStatus = true" type="primary" class="f-full"
                                           size="large">
                                    已选中{{ form.toList.length }}种语言
                                </el-button>
                            </div>
                        </div>
                        <div class="translation-query">
                            <el-input :maxlength="maxlength" show-word-limit v-model="form.q" placeholder="请输入要翻译的文本"
                                      type="textarea"/>
                        </div>
                        <div class="translation-btn">
                            <div class="left">
                                <el-button v-show="isShowBtn" @click="handleSaveVersion"
                                           :disabled="currentTranslateHistory?.saveFlag"
                                           plain type="warning">{{
                                    currentTranslateHistory?.saveFlag ? '已保存' : '保存翻译版本'
                                    }}
                                </el-button>
                            </div>
                            <div class="right">
                                <el-button v-show="isShowBtn" @click="handleClear" plain type="danger">清空</el-button>
                                <el-button v-show="isShowBtn" @click="handleTranslation" plain type="primary"
                                           :loading="loading">{{
                                    title
                                    }}
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <div class="translation-result">
                        <div class="result" v-for="key in Object.keys(translateResult)" :key="key">
                            <div class="top">
                                <div class="language">{{ languageMap?.[key] || "未识别的语言" }}</div>
                                <el-link :underline="false" class="copy"
                                         @click="handleCopySuccess(translateResult[key])">复制
                                    <el-icon style="margin-left:6px;">
                                        <DocumentCopy/>
                                    </el-icon>
                                </el-link>
                            </div>
                            <div class="bottom">
                                <div class="text">{{ translateResult?.[key] || "未找到该语言的翻译值" }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <!--翻译历史-->
                <TranslateHistory v-model:translateHistoryId="translateHistoryId"
                                  v-model:currentTranslateHistory="currentTranslateHistory" ref="translateHistoryRef"
                                  :product-id="form.productId"
                                  @tag-click="handleClickTranslationHistoryTag"/>
            </div>
        </el-form>
        <!--语言选择框-->
        <el-dialog @close="handleConfirmSelectLanguage" v-model="languageSelectStatus" title="语种选择">
            <el-form size="large" class="language-select-container" :model="form">
                <div class="language-search">
                    <el-input clearable v-model="languageSearchVal" placeholder="搜索语言"/>
                </div>
                <el-checkbox-group class="language-list" v-model="form.toList">
                    <div class="language-item" v-for="language in languageListCpt" :key="language.value">
                        <el-checkbox :label="language.value" border>{{ language.label }}</el-checkbox>
                    </div>
                </el-checkbox-group>
            </el-form>
            <template #footer>
                <div class="oper-btn">
                    <div class="left">
                        <el-button size="large" type="warning" plain @click="handleAllSelectLanguage">{{
                            allSelectLanguageStatus ? '取消全选' : '全选'
                            }}
                        </el-button>
                        <el-button size="large" type="danger" plain @click="form.toList = []">清空已选择的</el-button>
                        <el-button size="large" type="success" plain @click="handleCreateLanguageGroup"
                                   v-if="form.toList.length > 1">
                            编组
                        </el-button>
                    </div>
                    <div class="right">
                        <el-button size="large" type="danger" plain @click="languageSelectStatus=false">取消
                        </el-button>
                        <el-button size="large" type="primary" plain @click="languageSelectStatus=false">
                            确定
                        </el-button>
                    </div>
                </div>
                <el-divider/>
                <!--常用语言-->
                <LanguageGroup ref="languageGroupRef" @use-language-group="useLanguageGroup"
                               :language-list="languageList"/>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import {ref, getCurrentInstance, watch, computed,nextTick} from "vue";
import {selectListProduct} from "@/api/business/Product";
import {selectListLanguage} from "@/api/business/Language";
import {useClipboard} from "@vueuse/core";
import {addTranslate, saveTranslationVersionApi, youdaoTranslate} from "@/api/business/Translate";
import {debounceMs, maxlength} from "@/config";
import {addLanguageGroup} from "@/api/business/LanguageGroup";
import LanguageGroup from "@/components/LanguageGroup"
import NoticeForUse from "@/components/NoticeForUse"
import TranslateHistory from "@/components/TranslateHistory"

const source = ref()
const {text, copy, copied, isSupported} = useClipboard({source})
const {proxy} = getCurrentInstance();
const translateHistoryId = ref(-1);
const currentTranslateHistory = ref({saveFlag: false});//当前的翻译历史
const productList = ref([]);
const languageList = ref([]);
const languageMap = ref({});
// const translateResult = ref({en: "english", 'zh-CHS': "english", 'ko': "english"});
const languageSelectStatus = ref(false);
const translateResult = ref({});//翻译的结果
const flag = ref(false)
const loading = ref(false);
const title = ref("翻译");
const languageSearchVal = ref("");
const form = ref({
    productId: 1,
    q: "",
    from: "en",
    toList: ["zh-CHS"]
})

/**
 * 使用组语言
 */
const useLanguageGroup = (languageCode) => {
    form.value.toList = languageCode;
    handleConfirmSelectLanguage();
}
// 编组
const handleCreateLanguageGroup = () => {
    let data = {};
    let languageZhTitles = []
    let languageEnTitles = []
    form.value.toList.forEach(item => {
        languageZhTitles.push(languageList.value.find(x => x.value === item).label)
        languageEnTitles.push(languageList.value.find(x => x.value === item).en)
    })
    data.languageCodes = form.value.toList.join(',');
    data.languageZhTitles = languageZhTitles.join(',');
    data.languageEnTitles = languageEnTitles.join(',');
    addLanguageGroup(data).then(() => {
        proxy.$modal.msgSuccess("编组成功！");
        proxy.$refs['languageGroupRef'].getList && proxy.$refs['languageGroupRef'].getList();
    });
}
const timer = ref(0);
// 计算出搜索的语言
const languageListCpt = computed(() => {
    return languageList.value.filter(language => language.label?.match(languageSearchVal.value)) || [];
})
// 选择语言完成
const handleConfirmSelectLanguage = () => {
    languageSelectStatus.value = false;
    handleTranslation();
}
// 全选状态
const allSelectLanguageStatus = computed(() => {
    return form.value.toList.length === languageList.value.length;
});
/**
 * 全选/全不选
 */
const handleAllSelectLanguage = () => {
    if (allSelectLanguageStatus.value) {
        form.value.toList = [];
    } else {
        form.value.toList = languageList.value.map(x => x.value)
    }
    allSelectLanguageStatus.value = !allSelectLanguageStatus.value
}
/**
 * 自动翻译
 */
let watchState = watch(form, (value) => {
    clearTimeout(timer.value);
    if (!value.q.trim()) {
        loading.value = false;
        title.value = "翻译";
    } else {
        loading.value = true;
        title.value = "翻译中...";
    }
    translateResult.value = {};
    timer.value = setTimeout(() => {
        handleTranslation()
    }, debounceMs);
}, {
    deep: true
})
const isShowBtn = computed(() => {
    const {productId, from, toList, q} = form.value;
    // 产品ID不能为空
    const isProductIdValid = productId !== null;
    // 源不能为空
    const isFromValid = from !== "";
    // 目标语言不能为空
    const isToListValid = toList.length > 0;
    // 搜索关键字不能为空或空白字符
    const isQValid = q && q.trim();
    // 判断所有条件是否满足
    return isProductIdValid && isFromValid && isToListValid && isQValid;
});
/**
 * 保存翻译版本
 */
const handleSaveVersion = () => {
    if (translateHistoryId.value === -1) return;
    if (form.value.productId === null) return;
    if (form.value.from === "") return;
    if (form.value.toList.length === 0) return;
    if (!form.value.q || !form.value.q.trim()) return;
    const data = packData();
    saveTranslationVersionApi(data).then(() => {
        proxy.$modal.msgSuccess("保存成功！");
    }).finally(() => {
        proxy.$refs['translateHistoryRef'].getTranslationHistoryList && proxy.$refs['translateHistoryRef'].getTranslationHistoryList();
    });
}
/**
 * 打包版本数据
 * @returns {void|*}
 */
const packData = () => {
    const data = {
        translateVal: form.value.q?.trim(),
        languageCode: form.value.from,
        productId: form.value.productId,
        translateHistoryId: translateHistoryId.value,
        children: []
    }
    if (!currentTranslateHistory.value) {
        return proxy.msgError("保存失败!请重试")
    }
    let result = currentTranslateHistory.value.result;
    result = JSON.parse(result);
    Object.keys(result).forEach(languageCode => {
        data.children.push(
            {
                languageCode,
                translateVal: result[languageCode]
            }
        )
    })
    return data;
}
/**
 * 更换产品
 */
const handleChangeProduct = (val) => {
    form.value.q = "";
    nextTick(()=>{
        proxy.$refs['translateHistoryRef'].getTranslationHistoryList && proxy.$refs['translateHistoryRef'].getTranslationHistoryList();
    })
}
/**
 * 开始翻译
 */
const handleTranslation = () => {
    if (languageSelectStatus.value) return;
    if (form.value.productId === null) return;
    if (form.value.from === "") return;
    if (form.value.toList.length === 0) return;
    if (!form.value.q || !form.value.q.trim()) return;
    loading.value = true;
    title.value = "翻译中...";
    youdaoTranslate(form.value).then(res => {
        translateResult.value = res.data
    }).finally(() => {
        loading.value = false;
        title.value = "翻译";
        proxy.$refs['translateHistoryRef'].getTranslationHistoryList && proxy.$refs['translateHistoryRef'].getTranslationHistoryList();
    })
}
/**
 * 清空
 */
const handleClear = () => {
    form.value.q = "";
    translateResult.value = {};
}
/**
 * 复制成功提示
 */
const handleCopySuccess = (text) => {
    copy(text)
    proxy.$modal.msgSuccess("复制成功");
}
/**
 * 获取翻译产品
 */
const getProductList = () => {
    selectListProduct().then(res => {
        productList.value = res.data;
    })
}
/**
 * 获取所有语言
 */
const getLanguageList = () => {
    selectListLanguage().then(res => {
        languageList.value = res.data.map(x => {
            languageMap.value[x.languageCode] = x.zhName;//映射语言编码和语言的中文名称
            return {
                en: x.enName,
                label: x.zhName,
                value: x.languageCode
            }
        });
    })
}


/**
 * 点击翻译历史tag
 */
const handleClickTranslationHistoryTag = (history) => {
    watchState()
    const {
        q,
        fromLanguageCode: from,
        toLanguageCode: toList,
        result,
        translateHistoryId: _translateHistoryId
    } = history;
    translateHistoryId.value = _translateHistoryId;
    currentTranslateHistory.value = history;
    form.value = {
        ...form.value,
        q,
        from,
        toList: toList.split(',')
    }
    translateResult.value = JSON.parse(result)

    // 继续监听
    watchState = watch(form, (value) => {
        clearTimeout(timer.value);
        if (!value.q.trim()) {
            loading.value = false;
            title.value = "翻译";
        } else {
            loading.value = true;
            title.value = "翻译中...";
        }
        timer.value = setTimeout(() => {
            handleTranslation()
        }, debounceMs);
    }, {
        deep: true
    })
}

getProductList()
getLanguageList()
</script>
<style scoped lang="scss">
:deep(.el-dialog__footer) {
  text-align: unset;

  .oper-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.language-select-container {
  min-height: 350px;


  .language-search {
    margin-bottom: 20px;
  }

  .language-list {
    display: flex;
    flex-wrap: wrap;
  }

  .language-item {
    width: calc(100% / 6 - 20px);
    margin-right: 20px;
    margin-bottom: 20px;

    &:nth-child(6n) {
      margin-right: 0;
    }
  }
}

.translation-container {
  min-height: calc(100vh - 84px);
  padding: 0 200px;
  background: linear-gradient(to bottom, #D5DEE7 0%, #E8EBF2 50%, #E2E7ED 100%), linear-gradient(to bottom, rgba(0, 0, 0, 0.02) 50%, rgba(255, 255, 255, 0.02) 61%, rgba(0, 0, 0, 0.02) 73%), linear-gradient(33deg, rgba(255, 255, 255, 0.20) 0%, rgba(0, 0, 0, 0.20) 100%);
  background-blend-mode: normal, color-burn;
  user-select: none;

  :deep(.el-textarea__inner) {
    resize: unset;
    min-height: 250px !important;
    font-size: 24px;
    box-shadow: none !important;
  }

  :deep(.el-input__inner) {
    font-size: 18px;
    box-shadow: none !important;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none !important;
  }

  .translation-header {
    display: flex;
    align-items: center;
    padding: 20px 0;
    justify-content: space-between;
    //border-bottom: 1px solid rgba(64, 158, 255, 0.2);

    .translation-logo {
      display: flex;
      align-items: center;


      .logo-title {
        font-size: 34px;
        background: linear-gradient(to top, #409EFF 0%, #3c86ba 100%);
        --webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        font-weight: bold;
        text-shadow: 5px -10px 2px rgba(0, 0, 0, 0.1);
      }
    }

    img {
      border-radius: 50%;
      -webkit-filter: drop-shadow(5px -10px 2px rgba(0, 0, 0, 0.1));
      /*考虑浏览器兼容性：兼容 Chrome, Safari, Opera */
      filter: drop-shadow(5px -10px 2px rgba(0, 0, 0, 0.1));
      //margin-right: 20px;
    }
  }

  .translation-main {
    display: flex;
    margin-top: 20px;
    justify-content: flex-start;

    .translation-btn {
      margin-top: 20px;
      display: flex;
      //justify-content: flex-end;
      justify-content: space-between;
    }

    .language-select {
      display: flex;
      align-items: center;

      :deep(.el-select__tags-text),
      :deep(.el-select-v2__tags-text) {
        font-size: 18px;
      }


      .icon {
        margin: 0 10px;
      }

      .from-language {
        width: 180px !important;
      }

      .to-language {
        flex: 1;
      }
    }

    .translation-form {
      display: flex;
      flex-direction: column;
      width: 50%;

      .translation-query {
        margin-top: 20px;
      }
    }

    .translation-result {
      padding: 20px;
      background: #FFFFFF;
      flex: 1;
      margin-left: 10px;
      border-radius: 6px;
      max-height: 380px;
      transition: all .3s;
      overflow: auto;

      &:hover {
        box-shadow: var(--el-box-shadow);
      }

      .result {
        background: #fff;
        border-bottom: 1px solid #efefef;
        padding-bottom: 20px;
        margin-bottom: 20px;

        &:last-child {
          border-bottom: none;
          margin-bottom: 0;
        }

        .top {
          display: flex;
          align-items: center;
          margin-bottom: 20px;

          .language {
            margin-right: 20px;
            color: #409EFF;
            font-size: 18px;
          }

          .copy {
            cursor: pointer;
          }
        }
      }
    }

  }
}

// 屏幕大于 1024px 或小于 1440px 时应用该样式
@media screen and (min-width: 1600px) and (max-width: 1920px) {
  .translation-container {
    padding: 0 100px;
  }
}

@media screen and (min-width: 1366px) and (max-width: 1600px) {
  .translation-container {
    padding: 0 20px;
  }
}

@media screen and (max-width: 1365px) {
  .translation-container {
    padding: 0;
  }
}
</style>
